package com.power.sifa.correction.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.domain.ResponseDTO;
import com.plf.common.utils.ExcelUtil;
import com.power.sifa.aop.service.SMService;
import com.power.sifa.correction.api.ICrc_groupFeign;
import com.power.sifa.correction.model.Crc_group;
import com.power.sifa.correction.model.Crc_person;
import com.power.sifa.correction.model.pageInfo.Crc_groupPageInfo;
import com.power.sifa.correction.model.pojo.vo.Crc_groupVO;
import com.power.sifa.correction.service.Crc_groupService;
import com.power.sifa.correction.service.Crc_personService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;



/**
 *   社区矫正人员分组信息控制器
 */

@Slf4j
//@PowerLog
@RestController
@Api(value = "Crc_groupController",tags={"社区矫正人员分组信息"})
public class Crc_groupController implements ICrc_groupFeign {

    @Resource
    private Crc_groupService crc_groupService;

    @Resource
    private Crc_personService crc_personService;

    @Resource
    private SMService smService;

    
    @Override
    @ApiOperation("查询社区矫正人员分组信息分页列表")
    @SaCheckPermission("crc_group_list")
    public ResponseDTO list(Crc_groupPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo参数不能为空");
        Page<Crc_group> page = this.crc_groupService.findAll(pageInfo);
        List list = new ArrayList();
        if (!page.isEmpty()) {
            for (Crc_group crc_group : page) {
                crc_group.geneText();
                list.add(crc_group);
            }
        }
        PageDataResponse p = new PageDataResponse(list, page.getTotalElements(), page.getSize(), pageInfo.getPageNumber()<=1 ? 1 : pageInfo.getPageNumber());
        return ResponseDTO.succData(p);
    }

    @Override
    @ApiOperation("查看社区矫正人员分组信息")
    @SaCheckPermission("crc_group_view")
    public ResponseDTO view(String id) {
        Assert.notNull(id, "id不能为空");
        Crc_group crc_group  = crc_groupService.getById(id);
        if (crc_group != null) {
            crc_group.geneText();
        }
        return ResponseDTO.succData(crc_group);
    }

    @Override
    @ApiOperation("删除社区矫正人员分组信息")
    @SaCheckPermission("crc_group_del")
    public ResponseDTO delete(String id) {
        Assert.notNull(id, "id不能为空");
        crc_groupService.removeById(id);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation("保存或修改社区矫正人员分组信息")
    @SaCheckPermission("crc_group_save")
    public ResponseDTO save(Crc_group crc_group) {
        Assert.notNull(crc_group, "crc_group不能为空");
        crc_groupService.saveOrUpdate(crc_group);
        return ResponseDTO.succ();
    }
    
    @Override
    @ApiOperation(value="批量删除社区矫正人员分组信息")
    @SaCheckPermission("crc_group_del")
    public ResponseDTO batchDel(String ids) {
        Assert.isTrue(StringUtils.hasText(ids), "ids不能为空");
        List<String> list = Arrays.asList(ids.split(",")).stream().map(s -> s.trim()).collect(Collectors.toList());
        crc_groupService.removeByIds(list);
        return ResponseDTO.succ();
    }
    
    @Override
    @ApiOperation(value="导出excel")
    @SaCheckPermission("crc_group_list")
    public void output(HttpServletResponse response, Crc_groupPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo不能为空");
        String title = "社区矫正人员分组信息";
        String[] heads = {"序号","分组名称","描述","删除标记"};
        String[] fields = {"id","name","remark","deleted"};
        Page<Crc_group> page = this.crc_groupService.findAll(pageInfo);
        ExcelUtil.exportXls(title, heads, fields, page.getContent(), response);
    }
            
    @Override
    @ApiOperation(value="导出excel模板")
    public void exportExcelTemplate(HttpServletResponse response) {
        String title = "社区矫正人员分组信息";
        //id自增或list从表可自行删除，需与导入项一致
        String[] heads = {"序号","分组名称","描述","删除标记"};
        ExcelUtil.exportXls(title, heads, null, null, response);
    }
    
	@Override
	@ApiOperation(value="导入excel")
	public ResponseDTO importExcel(MultipartFile file) throws IOException {
        Assert.notNull(file, "file不能为空");
        //id自增或list从表可自行删除，需与下载的模板中导入项一致
        String[] fields = {"id","name","remark","deleted"};
        List<Crc_group> list = (List<Crc_group>)ExcelUtil.Import(fields, file, Crc_group.class);
        if(!CollectionUtils.isEmpty(list)) {
            this.crc_groupService.saveAll(list);
        }
        return ResponseDTO.succ();
	}

    @Override
    public ResponseDTO pageQuery(Crc_groupPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo参数不能为空");
        Page<Crc_group> page = this.crc_groupService.findAll(pageInfo);
        List<Crc_group> groupList = new ArrayList();
        if (!page.isEmpty()) {
            for (Crc_group crc_group : page) {
                crc_group.geneText();
                groupList.add(crc_group);
            }
        }
        List<Crc_groupVO> groupVOList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(groupList)) {
            List<String> groupIds = groupList.stream().map(Crc_group::getId).distinct().collect(Collectors.toList());
            // 查询对应的内部的分组的社矫人员
            Map<String, List<Crc_person>> personMap = crc_personService.findPersonByGroupIds(groupIds);
            groupVOList = BeanUtil.copyToList(groupList,Crc_groupVO.class);
            if (CollectionUtil.isNotEmpty(groupVOList) && ObjectUtil.isNotNull(personMap)) {
                // 进行遍历查询
                for(String groupId: personMap.keySet()) {
                    List<Crc_person> innerPersonList = personMap.get(groupId);
                    for (Crc_person person : innerPersonList) {
                        try {
                            person.geneText();
                            person.setPhone(smService.encrypt(person.getPhone()));
                            person.setName(smService.encrypt(person.getName()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    Crc_groupVO findOne = groupVOList.stream().filter(element -> element.getId().equals(groupId)).findFirst().orElse(null);
                    if (ObjectUtil.isNotNull(findOne)) {
                        findOne.setGroupPersons(innerPersonList);
                    }
                }
            }
        }
        PageDataResponse pageDataResponse = new PageDataResponse(groupVOList, page.getTotalElements(), page.getSize(),
                pageInfo.getPageNumber()<=1 ? 1 : pageInfo.getPageNumber());

        return ResponseDTO.succData(pageDataResponse);
    }

}
